import SimpleITK as sitk
import os

def dcm2nii(dcms_path, nii_path):

	# 1.构建dicom序列文件阅读器，并执行（即将dicom序列文件“打包整合”）
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(dcms_path)
    reader.SetFileNames(dicom_names)
    image2 = reader.Execute()
	# 2.将整合后的数据转为array，并获取dicom文件基本信息
    image_array = sitk.GetArrayFromImage(image2)  # z, y, x
    origin = image2.GetOrigin()  # x, y, z
    spacing = image2.GetSpacing()  # x, y, z
    direction = image2.GetDirection()  # x, y, z
	# 3.将array转为img，并保存为.nii.gz
    image3 = sitk.GetImageFromArray(image_array)
    image3.SetSpacing(spacing)
    image3.SetDirection(direction)
    image3.SetOrigin(origin)
    sitk.WriteImage(image3, os.path.join(nii_path,))



import nibabel as nib
import gzip
import shutil

def convert_nii_to_nii_gz(input_path, output_path):
    # 加载NIfTI文件
    nifti_img = nib.load(input_path)

    # 保存为NIfTI压缩文件
    nib.save(nifti_img, output_path)



def convert_raw_mhd_to_niigz(input_folder_path, output_folder):
    # 获取文件夹内的所有文件
    file_list = os.listdir(input_folder_path)

    for file_name in file_list:
        # 获取文件的完整路径
        file_path = os.path.join(input_folder_path, file_name)

        if file_name.endswith('.mhd'):
            # 读取.mhd文件及对应的.raw文件
            image = sitk.ReadImage(file_path)
            raw_file_path = os.path.splitext(file_path)[0] + '.raw'

            # 构建输出文件路径及文件名
            output_file = output_folder#os.path.join(output_folder, os.path.splitext(file_name)[0] + '.nii.gz')

            #
            # 设置.raw文件的元数据
            image.SetMetaData("raw_file", raw_file_path)

            # 保存为.nii.gz格式

            sitk.WriteImage(image, output_file)

            # 打印转换成功的信息
            print(f"Converted {file_name} to {output_file}")




if __name__ == '__main__':

    # dcm_path = r'D:\Astudy\python\feijiang\data\dcm\t1c'
    # save_path = r'D:\Astudy\python\feijiang\data\dcm\tras'
    #
    # dcm2nii(dcm_path, save_path+f'/ok.nii.gz')

    # # 调用转换函数
    # input_file = r'D:\Astudy\python\feijiang\data\nii\002liushide_t1c.nii'
    # output_file = r'D:\Astudy\python\feijiang\data\nii\ok.nii.gz'
    #
    # convert_nii_to_nii_gz(input_file, output_file)

    input_folder = r'D:\Astudy\python\vue-flask-Paddle\upload\transformData\raw\a010'  # 输入文件夹路径
    output_folder = r'D:\Astudy\python\vue-flask-Paddle\upload\transformData\raw'  # 输出文件夹路径
    convert_raw_mhd_to_niigz(input_folder, output_folder)



